package org.jiucheng.magpiebridge.server.aio.proxy;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.atomic.AtomicInteger;

import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.server.aio.ClientWriteAttachment;
import org.jiucheng.magpiebridge.server.aio.ClientWriteCompletionHandler;

public class ProxyServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, ProxyServerAttachment> {
    
    private static final AtomicInteger CLIENTS_ID = new AtomicInteger();

    public void completed(AsynchronousSocketChannel result, ProxyServerAttachment attachment) {
        attachment.getProxyServer().accept(attachment, this);
        
        Message message = new Message();
        message.setMagic(Message.MAGIC);
        message.setType(Message.Type.CONNECT);
        message.setUri(CLIENTS_ID.incrementAndGet());
        byte[] data = attachment.getRemote().getBytes();
        message.setData(data);
        message.setSize(data.length);
        
        ByteBuffer writeBuffer = Message.toByteBuffer(message);
        attachment.getClientAttachment().putProxy(message.getUri(), new ProxyClientWriteAttachment(result).setClientAttachment(attachment.getClientAttachment()));
        
        while (!attachment.getClientAttachment().writed.compareAndSet(false, true)) {}
        attachment.getClientAttachment().getAsynchronousSocketChannel().write(writeBuffer, new ClientWriteAttachment(writeBuffer, attachment).setProxyAsynchronousSocketChannel(result).setUri(message.getUri()), new ClientWriteCompletionHandler());
    }

    public void failed(Throwable exc, ProxyServerAttachment attachment) {
        attachment.getClientAttachment().writed.compareAndSet(true, false);
        System.out.println("proxy server failed");
    }
}
